package com.bawei.module_mine.mine

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.BaseApplication
import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_common.base.flow_eventbus.core.EventBusCore
import com.bawei.lib_common.base.state.UILoader
import com.bawei.lib_common.base.state.UIState
import com.bawei.lib_common.base.utils.LoggerUtils
import com.bawei.lib_common.base.utils.ToastUtils
import com.bawei.lib_net.storage.AuthMMKV
import com.bawei.module_mine.R
import com.bawei.module_mine.adapter.MineAdapter
import com.bawei.module_mine.databinding.FragmentMineBinding
import com.bawei.module_mine.databinding.LayoutMineContentBinding
import com.bawei.module_mine.login.LoginActivity
import com.bawei.module_mine.model.LoginSuccessEvent
import com.bawei.myclub.base.mvvm.view.BaseFragment
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job

@AndroidEntryPoint
@Route(path = Router.Ui.MineFragment)
class MineFragment : BaseFragment<MineViewModel, FragmentMineBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_mine
    override val mViewModel: MineViewModel by viewModels()
    private var observeJob: Job? = null // 用于管理观察者协程
    private val mMineAdapter: MineAdapter by lazy {
        MineAdapter(
            onApplyforItemClick = {
                ARouter.getInstance().build(Router.Ui.ApplyForActivity).navigation()
            },
            onAuditItemClick = {
                ARouter.getInstance().build(Router.Ui.AuditActivity).navigation()
            }
        )
    }

    override fun initView() {
        initHeard()
        initEvent()
        initAdapter()
    }

    private fun initAdapter() {
        mMineAdapter.setupLayoutManager(mBinding.layoutRec)
        mBinding.layoutRec.adapter = mMineAdapter
    }

    override fun initData() {
        // 加载数据（模拟网络请求）
        if (AuthMMKV.token.trim().isBlank()){
            mViewModel.loadServiceNoLoginList()
        }else{
            mViewModel.loadServiceList()
        }
        mViewModel.loadStatisticsList()
    }

    override fun initListener() {
        mBinding.loginHead.loginHeadHead.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.LoginActivity).navigation()
        }
        // 观察服务列表数据变化
        mViewModel.serviceList.observe(this) { list ->
            mMineAdapter.setFunctionData(list)
            LoggerUtils.d("MineFragment", list.toString())
        }

        // 观察统计数据变化（假设需要显示在 TextView 中）
        mViewModel.statisticsList.observe(this) { stats ->
            mMineAdapter.setStatisticsData(stats)
            LoggerUtils.d("MineFragment", stats.toString())
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        observeJob?.cancel()
    }

    override fun onResume() {
        super.onResume()
        initHeard()
    }
    private fun initEvent() {
        // 通过 ViewModelProvider 获取 EventBusCore 实例（与 Fragment 生命周期绑定）
        val eventBusCore = ViewModelProvider(requireActivity())[EventBusCore::class.java]
        // 接收普通事件（仅当前活跃页面接收）
        observeJob = eventBusCore.observeEvent<LoginSuccessEvent>(
            lifecycleOwner = this,          // 绑定当前页面的生命周期
            eventName = "LoginSuccessEvent",// 事件名（与发送时一致）
            minState = Lifecycle.State.RESUMED, // 最小生命周期状态（如 RESUMED）
            dispatcher = Dispatchers.Main,  // 主线程处理（UI 更新）
            isSticky = false,               // 非粘性事件
            onReceived = { event->
                LoggerUtils.d("MineFragment", event.text.toString())
            }
        )
    }
    private fun initHeard() {
        if (AuthMMKV.token.trim().isBlank()){
            mBinding.loginHead.apply {
                loginHeadPen.visibility = View.GONE
                loginHeadPlane.visibility = View.GONE
                loginHeadUsername.visibility = View.GONE
            }
        }else{
            mBinding.loginHead.apply {
                loginHeadPen.visibility = View.VISIBLE
                loginHeadPlane.visibility = View.VISIBLE
                loginHeadUsername.visibility = View.VISIBLE
                loginHeadUsername.text = AuthMMKV.username
                loginHeadHead.visibility = View.GONE
                loginHeadHeadTwo.visibility = View.VISIBLE
            }
        }
    }
}